package com.chs.service.impl;

import com.chs.model.Order;
import com.chs.model.Product;
import com.chs.model.ProductOrder;
import com.chs.model.ShoppingCart;
import com.chs.model.User;
import com.chs.model.dto.OrderDto;
import com.chs.model.dto.ProductDto;
import com.chs.dao.OrderMapper;
import com.chs.dao.ProductMapper;
import com.chs.dao.UserMapper;
import com.chs.service.OrderService;
import com.chs.service.ProductOrderService;
import com.chs.service.ShoppingCartService;
import com.chs.util.SourceUtil;
import com.chs.util.TXTUtil;
import com.chs.util.TokenUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.hutool.core.date.DateUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * (Order)表服务实现类
 *
 * @author mopeiwen
 * @since 2020-06-10 10:48:17
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
	@Resource
	private OrderMapper orderMapper;
	@Resource
	private ProductMapper productMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private ShoppingCartService shoppingCartService;
	@Resource
	private ProductOrderService productOrderService;
	@Autowired
	private HttpServletRequest request;

	/**
	 * 获得订单信息 以下两个参数不会同时存在
	 * 
	 * @param pid   单个商品下单
	 * @param scids 购物车下单 多个商品
	 * @return
	 */
	@Override
	public OrderDto queryById(String pid_count, String scids) {
		String uid = TokenUtil.getUserId(request.getHeader("Authorization"));
		User user = userMapper.selectByPrimaryKey(uid);
		OrderDto orderDto = new OrderDto();
		ArrayList<ProductDto> productDtos = new ArrayList<>();

		// 填充用户信息
		orderDto.setUser(user);

		// 单个商品下单
		if (pid_count != null && !pid_count.equals("")) {
			String pid = pid_count.split("_")[0];
			// 购买商品的数量
			Integer count = Integer.valueOf(pid_count.split("_")[1]);
			Product product = productMapper.selectByPrimaryKey(pid);
			System.out.println(product);

			// 填充商品信息
			ProductDto productDto = new ProductDto(product.getPid(), product.getName(), product.getPrice(),
					product.getFare(), count,
					TXTUtil.splitAndSplice(product.getPicture(), ",", SourceUtil.getPictureUrl()));

			productDtos.add(productDto);
			orderDto.setProducts(productDtos);

			return orderDto;
		}

		// 多个商品下单
		if (scids != null && !scids.equals("")) {
			// 遍历购物项
			String[] shoppingCarts = TXTUtil.valueToStr(scids, ",");
			for (String scid : shoppingCarts) {
				ShoppingCart shoppingCart = shoppingCartService.queryById(scid);
				ProductDto productDto = new ProductDto(shoppingCart.getProduct().getPid(),
						shoppingCart.getProduct().getName(), shoppingCart.getProduct().getPrice(),
						shoppingCart.getProduct().getFare(), shoppingCart.getCount(), TXTUtil.splitAndSplice(
								shoppingCart.getProduct().getPicture(), ",", SourceUtil.getPictureUrl()));
				productDtos.add(productDto);
			}

			orderDto.setProducts(productDtos);
			return orderDto;
		}

		return null;
	}

	/**
	 * 确认订单
	 * 
	 * @param orderDto
	 * @return
	 */
	@Override
	public String insertOrder(OrderDto orderDto) {
		Map<String, BigDecimal> map = new HashMap<>();// 缓存价格 格式 <uid,totalprice>
		Map<String, String> map2 = new HashMap<>();// 缓存订单ID <uid,oid>

		// 用户ID
		String uid = TokenUtil.getUserId(request.getHeader("Authorization"));

		String oids = "";

		// 订单总价 需要计算
		// bignum3 = bignum1.add(bignum2); 加
		// bignum3 = bignum1.subtract(bignum2); 减
		// bignum3 = bignum1.multiply(bignum2); 乘
		// bignum3 = bignum1.divide(bignum2); 除

		// 计算总价 按卖家分类保存总价
		for (ProductDto productDto : orderDto.getProducts()) {
			BigDecimal totalprice = new BigDecimal(0);
			Product product = productMapper.selectByPrimaryKey(productDto.getPid());
			// 计算单个购物项价格
			totalprice = totalprice.add(product.getPrice().multiply(new BigDecimal(productDto.getCount())));

			if (map.containsKey(product.getUid())) { // 如果有这个购物项记录
				BigDecimal val = map.get(product.getUid());
				val = val.add(totalprice);
				map.put(product.getUid(), val);
			} else {
				// 加上运费
				totalprice = totalprice.add(product.getFare());
				map.put(product.getUid(), totalprice);
			}
		}

		// 添加订单
		for (Entry<String, BigDecimal> entry : map.entrySet()) {
			// 填充订单
			Order order = new Order(uid, orderDto.getUser().getName(), orderDto.getUser().getAddress(),
					orderDto.getUser().getPhone(), DateUtil.now(), null, null, null, orderDto.getOrderType(), 0,
					entry.getValue());

			// 写入订单
			orderMapper.insertSelective(order);

			// 记录oid
			map2.put(entry.getKey(), order.getOid());

			if (oids != null && !oids.equals("")) {
				oids = oids + "," + order.getOid();
			} else {
				oids = order.getOid();
			}

		}

		// 循环插入订单记录项
		for (ProductDto productDto : orderDto.getProducts()) {
			Product product = productMapper.selectByPrimaryKey(productDto.getPid());

			ProductOrder productOrder = new ProductOrder(null, productDto.getPid(), map2.get(product.getUid()),
					productDto.getCount());
			productOrderService.insert(productOrder);
		}

		return oids;
	}

	/**
	 * 支付成功修改订单记录
	 *
	 * @param oid 主键
	 * @return 实例对象
	 */
	@Override
	public boolean orderPay(String oid) {
		String[] oids = TXTUtil.valueToStr(oid, ",");
		for (String ss : oids) {
			Order order = new Order();
			order.setOid(ss);
			order.setPaytime(DateUtil.now());
			order.setOrderflag(1);
			
			this.orderMapper.updateByPrimaryKeySelective(order);
		}
		
		return true;
	}

	/**
	 * 通过订单ID查询单条订单数据
	 *
	 * @param oid 主键
	 * @return 实例对象
	 */
	@Override
	public Order queryById(String oid) {
		Order order = this.orderMapper.selectByPrimaryKey(oid);

		// 防止指针指向相同的对象
		Product product = new Product();
		for (int i = 0; i < order.getProductOrders().size(); i++) {
			product = order.getProductOrders().get(i).getProduct();
			if (product.getPicture().contains("http")) {
				continue;
			}

			order.getProductOrders().get(i).getProduct().setPicture(TXTUtil.splitAndSplice(
					order.getProductOrders().get(i).getProduct().getPicture(), ",", SourceUtil.getPictureUrl()));
			System.out.println(order.getProductOrders().get(i).getProduct().getPicture());
		}

		return this.orderMapper.selectByPrimaryKey(oid);
	}

	/**
	 * 通过Order对象查询订单列表
	 *
	 * @param order 实例对象
	 * @return 实例对象
	 */
	@Override
	public PageInfo<Order> selectAll(int pageNum, int pageSize, int flag) {
		// 用户ID
		String uid = TokenUtil.getUserId(request.getHeader("Authorization"));
		// pageNum代表页码值，pageSize代表每页条数
		PageHelper.startPage(pageNum, pageSize);

		Order order = new Order();
		order.setUid(uid);
		order.setOrderflag(flag);

		// 使用PageInfo来封装查询的数据
		PageInfo<Order> pageInfo = new PageInfo<Order>(orderMapper.selectAll(order));

		// 防止指针指向相同的对象
		Product product = new Product();

		for (int j = 0; j < pageInfo.getList().size(); j++) {
			order = pageInfo.getList().get(j);

			for (int i = 0; i < order.getProductOrders().size(); i++) {
				product = order.getProductOrders().get(i).getProduct();
				if (product.getPicture().contains("http")) {
					continue;
				}

				order.getProductOrders().get(i).getProduct().setPicture(TXTUtil.splitAndSplice(
						order.getProductOrders().get(i).getProduct().getPicture(), ",", SourceUtil.getPictureUrl()));
				System.out.println(order.getProductOrders().get(i).getProduct().getPicture());
			}

			pageInfo.getList().set(j, order);
		}

		return pageInfo;
	}

	@Override
	public PageInfo<Order> selectAll(int pageNum, int pageSize) {
		// pageNum代表页码值，pageSize代表每页条数
		PageHelper.startPage(pageNum, pageSize);

		// 使用PageInfo来封装查询的数据
		PageInfo<Order> pageInfo = new PageInfo<Order>(orderMapper.selectAll());

		// 防止指针指向相同的对象
		Product product = new Product();
		for (int j = 0; j < pageInfo.getList().size(); j++) {
			Order order = pageInfo.getList().get(j);

			for (int i = 0; i < order.getProductOrders().size(); i++) {
				product = order.getProductOrders().get(i).getProduct();
				if (product.getPicture().contains("http")) {
					continue;
				}

				order.getProductOrders().get(i).getProduct().setPicture(TXTUtil.splitAndSplice(
						order.getProductOrders().get(i).getProduct().getPicture(), ",", SourceUtil.getPictureUrl()));
				System.out.println(order.getProductOrders().get(i).getProduct().getPicture());
			}

			pageInfo.getList().set(j, order);
		}

		return pageInfo;
	}

	@Override
	public PageInfo<Order> selectAllMySold(int pageNum, int pageSize) {
		// 用户ID
		String uid = TokenUtil.getUserId(request.getHeader("Authorization"));
		
		// pageNum代表页码值，pageSize代表每页条数
		PageHelper.startPage(pageNum, pageSize);

		// 使用PageInfo来封装查询的数据
		PageInfo<Order> pageInfo = new PageInfo<Order>(orderMapper.selectAllMySold(uid));

		// 防止指针指向相同的对象
		Product product = new Product();
		for (int j = 0; j < pageInfo.getList().size(); j++) {
			Order order = pageInfo.getList().get(j);

			for (int i = 0; i < order.getProductOrders().size(); i++) {
				product = order.getProductOrders().get(i).getProduct();
				if (product.getPicture().contains("http")) {
					continue;
				}

				order.getProductOrders().get(i).getProduct().setPicture(TXTUtil.splitAndSplice(
						order.getProductOrders().get(i).getProduct().getPicture(), ",", SourceUtil.getPictureUrl()));
				System.out.println(order.getProductOrders().get(i).getProduct().getPicture());
			}

			pageInfo.getList().set(j, order);
		}

		return pageInfo;
	}

	/**
	 * 新增数据
	 *
	 * @param order 实例对象
	 * @return 实例对象
	 */
	@Override
	public boolean insert(Order order) {
		return this.orderMapper.insertSelective(order)>0;
	}

	/**
	 * 修改数据
	 *
	 * @param order 实例对象
	 * @return 实例对象
	 */
	@Override
	public boolean update(Order order) {
		return this.orderMapper.updateByPrimaryKeySelective(order)>0;
	}

	/**
	 * 通过主键删除数据
	 *
	 * @param oid 主键
	 * @return 是否成功
	 */
	@Override
	public boolean deleteById(String oid) {
		return this.orderMapper.deleteByPrimaryKey(oid) > 0;
	}

	/**
	 * 批量删除订单
	 */
	@Override
	public boolean batchdeleteOrder(String oid) {
		ArrayList<String> oidList = new ArrayList<String>();
		String[] strs = oid.split(",");
		for (String str : strs) {
			oidList.add(str);
		}
		return orderMapper.batchdeleteOrder(oidList)>0;
	}

	/**
	 * 填写物流号
	 * 
	 * @param oid
	 * @param logisticsNo
	 * @return
	 */
	@Override
	public boolean writeLogNo(String oid, String logisticsNo) {
		Order order = new Order();
		order.setOid(oid);
		order.setLogisticsno(logisticsNo);

		order.setOrderflag(2);
		return this.orderMapper.updateByPrimaryKeySelective(order) > 0;
	}

	/**
	 * 确认收货
	 * 
	 * @param oid
	 * @return
	 */
	@Override
	public boolean okReceipt(String oid) {
		Order order = new Order();
		order.setOid(oid);
		order.setReceipttime(DateUtil.now());

		order.setOrderflag(3);
		return this.orderMapper.updateByPrimaryKeySelective(order) > 0;
	}

}